<?php
namespace frontend\models;

use common\components\SmsCaptcha\CaptchaValidator;
use common\components\SmsRonglian\SmsRonglian;
use common\models\c2\entity\FeUser;
use common\models\c2\entity\UserGrade;
use common\models\c2\entity\UserInviteCode;
use common\models\c2\statics\UserGradeState;
use cza\base\models\ModelTrait;
use Yii;
use yii\base\Model;
use common\models\User;

/**
 * Signup form
 */
class SignupForm extends Model
{
    use ModelTrait;
    public $username;
    public $mobile_number;
    public $email;
    public $password;
    public $verify_code;
    public $invite_code;


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['username', 'unique', 'targetClass' => '\common\models\c2\entity\FeUser', 'message' => Yii::t('app.c2', 'This username has already been taken.')],
            ['username', 'string', 'min' => 2, 'max' => 255],

            [['password', 'mobile_number', 'verify_code', 'username'], 'required'],
            [['mobile_number',], 'match', 'pattern' => '/^1[0-9]{10}$/', 'message' => Yii::t('app.c2', '{attribute} must be mobile format!')],
            [['mobile_number'], 'string', 'length' => 11],
            [['mobile_number'], 'number', 'integerOnly' => true],
            [['username', 'mobile_number'], 'unique', 'targetClass' => FeUser::className(), 'message' => Yii::t('app.c2', '{attribute} "{value}" has already been taken.')],
            // [['username', 'mobile_number'], FeUserUniqueValidator::className(), 'targetClass' => FeUserModel::className(), 'message' => Yii::t('app.c2', '{attribute} "{value}" has already been taken.')],

            // ['email', 'email'],
            // ['email', 'string', 'max' => 255],
            // ['email', 'unique', 'targetClass' => '\common\models\FeUserModel', 'message' => 'This email address has already been taken.'],
            ['password', 'string', 'min' => 6],

            ['verify_code', CaptchaValidator::className()],

            ['invite_code', 'trim'],
            ['invite_code', \frontend\components\rules\InviteCodeValidator::className()],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'mobile_number' => Yii::t('app.c2', 'Mobile Number'),
            'password' => Yii::t('app.c2', 'Password'),
            'verify_code' => Yii::t('app.c2', 'Sms code'),
            'username' => Yii::t('app.c2', 'Username'),
        ];
    }

    /**
     * Signs user up.
     *
     * @return FeUser|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }

        $user = new FeUser();
        $user->username = $this->username;
        $user->mobile_number = $this->mobile_number;
        $user->setPassword($this->password);
        $user->generateAuthKey();

        Yii::info($this->invite_code);

        $userInviteCode = UserInviteCode::findOne(['code' => $this->invite_code]);

        if (!is_null($userInviteCode)) {
            // Yii::info($userInviteCode);
            $db = Yii::$app->db->beginTransaction();

            // Invite user Model
            $inviteUser = $userInviteCode->user;
            // Update user attributes
            $user->invite_user_id = $inviteUser->id;
            $user->invite_username = $inviteUser->username;

            // Create invite user grade
            $inviteUserGrade = new UserGrade();
            $inviteUserGrade->amoeba_id = $userInviteCode->amoeba_id;
            $inviteUserGrade->invite_user_id = $userInviteCode->user_id;
            $inviteUserGrade->state = UserGradeState::STATE_INIT;

            if ($user->save()) {
                $inviteUserGrade->join_user_id = $user->id;
                if ($inviteUserGrade->save()) {
                    $db->commit();
                    return $user;
                }
            }
            $db->rollBack();
        }

        return $user->save() ? $user : null;
    }
}
